package org.jeecg.modules.basic.entry.util;

import org.springframework.util.StreamUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Map;
import javax.net.ssl.SSLException;
import java.io.*;
import java.net.HttpURLConnection;
import java.util.Iterator;
import java.util.UUID;

import static org.jeecg.modules.basic.entry.util.StringUtil.getMD5;


public class HttpRequestToPrivate {
    /**
     * 向指定URL发送GET方法的请求
     *
     * @param url   发送请求的URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            System.out.println("url:" + urlNameString);
            String timestamp = String.valueOf(System.currentTimeMillis());
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            connection.setRequestProperty("appKey", SenseTimeEnumToPrivate.APP_KEY.getMsg());
            connection.setRequestProperty("timestamp", timestamp);
            connection.setRequestProperty("sign", getMD5(timestamp + "#" + SenseTimeEnumToPrivate.APP_SECRET.getMsg()));
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @return 所代表远程资源的响应结果
     */

    public static byte[] sendPost(String strUrl, Map<String, Object> params, Map<String, byte[]> fileParams, String name) throws Exception {
        String BOUNDARY = UUID.randomUUID().toString().replace("-", "");
        String timestamp = String.valueOf(System.currentTimeMillis());
        URL url = new URL(strUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setUseCaches(false);
        connection.setInstanceFollowRedirects(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Accept", "application/json, text/plain, */*"); // 设置接收数据的格式
        connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); // 设置发送数据的格式
        connection.setRequestProperty("appKey", SenseTimeEnumToPrivate.APP_KEY.getMsg());
        connection.setRequestProperty("timestamp", timestamp);
        connection.setRequestProperty("sign", getMD5(timestamp + "#" + SenseTimeEnumToPrivate.APP_SECRET.getMsg()));


        connection.connect();
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        params.forEach((key, value) -> {
            try {
                out.writeBytes("--" + BOUNDARY + "\r\n");
                out.writeBytes("Content-Disposition: form-data; name=\"" + key + "\"");
                out.writeBytes("\r\n\r\n");
                out.write((value + "\r\n").getBytes());
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        if (fileParams != null && fileParams.size() > 0) {
            fileParams.forEach((key, value) -> {
                try {
                    out.writeBytes("--" + BOUNDARY + "\r\n");
                    out.writeBytes("Content-Disposition: form-data; name=\"" + key
                            + "\"; filename=\"" + name + "\"");
                    out.writeBytes("\r\n");
                    out.writeBytes("Content-Type: image/jpeg");//此处很关键
                    out.writeBytes("\r\n\r\n");
                    out.write(value);
                    out.writeBytes("\r\n");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        }

        out.writeBytes("--" + BOUNDARY + "--");
        out.flush();
        out.close();
        InputStream in = null;
        int code = connection.getResponseCode();
        try {
            if (code == 200) {
                in = connection.getInputStream();
            } else {
                in = connection.getErrorStream();
            }
        } catch (SSLException e) {
            e.printStackTrace();
            return new byte[0];
        }
        ByteArrayOutputStream baout = new ByteArrayOutputStream();
        byte[] buff = new byte[1024];
        int len;
        while ((len = in.read(buff)) != -1) {
            baout.write(buff, 0, len);
        }
        byte[] bytes = baout.toByteArray();
        in.close();
        return bytes;
    }


    /**
     * 参数json为json格式的字符串
     * @param urlStr
     * @param json
     * @return
     */
    public static String sendPostByJSON(String urlStr, String json) {
        OutputStreamWriter outputStreamWriter = null;
        BufferedReader bufferedReader = null;
        String response = "";
        String timestamp = String.valueOf(System.currentTimeMillis());
        try {
            URL url = new URL(urlStr);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);
            connection.setRequestMethod("POST");      //POST需大写
            connection.setRequestProperty("content-Type", "application/json");        //设置数据格式为json
            connection.setRequestProperty("charset", "utf-8");
            connection.setRequestProperty("appKey", SenseTimeEnumToPrivate.APP_KEY.getMsg());
            connection.setRequestProperty("timestamp", timestamp);
            connection.setRequestProperty("sign", getMD5(timestamp + "#" + SenseTimeEnumToPrivate.APP_SECRET.getMsg()));//设置编码格式为utf-8
            connection.setConnectTimeout(3000); // 3秒 连接主机的超时时间（单位：毫秒）
            connection.setReadTimeout(3000); // 5秒 从主机读取数据的超时时间（单位：毫秒）
            connection.connect();

            outputStreamWriter = new OutputStreamWriter(connection.getOutputStream());
            outputStreamWriter.append(json);
            outputStreamWriter.flush();

            bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
            String line = "";
            while((line = bufferedReader.readLine()) != null) {
                response += line;
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                outputStreamWriter.close();
                bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return response;
    }

    /**
     * 参数json为json格式的字符串
     * @param urlStr
     * @param json
     * @return
     */
    public static String sendPutByJSON(String urlStr, String json) {
        OutputStreamWriter outputStreamWriter = null;
        BufferedReader bufferedReader = null;
        String response = "";
        String timestamp = String.valueOf(System.currentTimeMillis());
        try {
            URL url = new URL(urlStr);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);
            connection.setRequestMethod("PUT");      //POST需大写
            connection.setRequestProperty("content-Type", "application/json");        //设置数据格式为json
            connection.setRequestProperty("charset", "utf-8");
            connection.setRequestProperty("appKey", SenseTimeEnumToPrivate.APP_KEY.getMsg());
            connection.setRequestProperty("timestamp", timestamp);
            connection.setRequestProperty("sign", getMD5(timestamp + "#" + SenseTimeEnumToPrivate.APP_SECRET.getMsg()));//设置编码格式为utf-8
            connection.connect();

            outputStreamWriter = new OutputStreamWriter(connection.getOutputStream());
            outputStreamWriter.append(json);
            outputStreamWriter.flush();

            bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
            String line = "";
            while((line = bufferedReader.readLine()) != null) {
                response += line;
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                outputStreamWriter.close();
                bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return response;
    }

}

